<!DOCTYPE HTML>
<html lang="zh-CN">


<head><meta name="generator" content="Hexo 3.8.0">
    <meta charset="utf-8">
    <meta name="keywords" content="Autorelease解读, Swift, iOS, Python">
    <meta name="description" content="群组欢迎加入群组,闲聊工作&amp;amp;技术&amp;amp;问题等

&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;Autorelease翻译过来就是自动释放,什么是自动释放,怎么自动释放,什么时候自">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <title>Autorelease解读 | waitwalker</title>
    <link rel="icon" type="image/png" href="/favicon.png">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/font-awesome.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">
    <style type="text/css">
        
    </style>

    <script src="/libs/jquery/jquery-2.2.0.min.js"></script>
<link rel="stylesheet" href="/css/prism-tomorrow.css" type="text/css"></head>


<body>

<!--导航-->

<header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    <!---->
                    <!--<img src="/medias/logo.png" class="logo-img" alt="LOGO">-->
                    <!---->
                    <span class="logo-span">waitwalker</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fa fa-navicon"></i></a>
<ul class="right">
    
    <li class="hide-on-med-and-down">
        <a href="/" class="waves-effect waves-light">
            
            <i class="fa fa-home"></i>
            
            <span>首页</span>
        </a>
    </li>
    
    <li class="hide-on-med-and-down">
        <a href="/tags" class="waves-effect waves-light">
            
            <i class="fa fa-tags"></i>
            
            <span>标签</span>
        </a>
    </li>
    
    <li class="hide-on-med-and-down">
        <a href="/categories" class="waves-effect waves-light">
            
            <i class="fa fa-bookmark"></i>
            
            <span>分类</span>
        </a>
    </li>
    
    <li class="hide-on-med-and-down">
        <a href="/archives" class="waves-effect waves-light">
            
            <i class="fa fa-archive"></i>
            
            <span>归档</span>
        </a>
    </li>
    
    <li class="hide-on-med-and-down">
        <a href="/about" class="waves-effect waves-light">
            
            <i class="fa fa-user-circle-o"></i>
            
            <span>关于</span>
        </a>
    </li>
    
    <li class="hide-on-med-and-down">
        <a href="/friends" class="waves-effect waves-light">
            
            <i class="fa fa-address-book"></i>
            
            <span>友情链接</span>
        </a>
    </li>
    
    <li>
        <a href="#searchModal" class="modal-trigger waves-effect waves-light">
            <i id="searchIcon" class="fa fa-search" title="搜索"></i>
        </a>
    </li>
</ul>

<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">waitwalker</div>
        <div class="logo-desc">
            
            Life is measured by thought and action not by time.
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li>
            <a href="/" class="waves-effect waves-light">
                
                <i class="fa fa-fw fa-home"></i>
                
                首页
            </a>
        </li>
        
        <li>
            <a href="/tags" class="waves-effect waves-light">
                
                <i class="fa fa-fw fa-tags"></i>
                
                标签
            </a>
        </li>
        
        <li>
            <a href="/categories" class="waves-effect waves-light">
                
                <i class="fa fa-fw fa-bookmark"></i>
                
                分类
            </a>
        </li>
        
        <li>
            <a href="/archives" class="waves-effect waves-light">
                
                <i class="fa fa-fw fa-archive"></i>
                
                归档
            </a>
        </li>
        
        <li>
            <a href="/about" class="waves-effect waves-light">
                
                <i class="fa fa-fw fa-user-circle-o"></i>
                
                关于
            </a>
        </li>
        
        <li>
            <a href="/friends" class="waves-effect waves-light">
                
                <i class="fa fa-fw fa-address-book"></i>
                
                友情链接
            </a>
        </li>
        
        
        <li><div class="divider"></div></li>
        <li>
            <a href="https://github.com/waitwalker" class="waves-effect waves-light" target="_blank">
                <i class="fa fa-github-square fa-fw"></i>Fork Me
            </a>
        </li>
        
    </ul>
</div>

        </div>

        
            <style>
    .nav-transparent .github-corner {
        display: none !important;
    }

    .github-corner {
        position: absolute;
        z-index: 10;
        top: 0;
        right: 0;
        border: 0;
        transform: scale(1.1);
    }

    .github-corner svg {
        color: #0f9d58;
        fill: #fff;
        height: 64px;
        width: 64px;
    }

    .github-corner:hover .octo-arm {
        animation: a 0.56s ease-in-out;
    }

    .github-corner .octo-arm {
        animation: none;
    }

    @keyframes a {
        0%,
        to {
            transform: rotate(0);
        }
        20%,
        60% {
            transform: rotate(-25deg);
        }
        40%,
        80% {
            transform: rotate(10deg);
        }
    }
</style>

<a href="https://github.com/waitwalker" class="github-corner tooltipped hide-on-med-and-down" target="_blank" data-tooltip="https://github.com/waitwalker" data-position="left" data-delay="50">
    <svg viewbox="0 0 250 250" aria-hidden="true">
        <path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"/>
        <path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"/>
        <path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"/>
    </svg>
</a>
        
    </nav>

</header>





<div class="bg-cover pd-header post-cover" style="background-image: url('/medias/featureimages/8.jpg')">
    <div class="container">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <div class="description center-align post-title">
                        Autorelease解读
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>



<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        margin: 35px 0 15px 0;
        padding-left: 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #toc-content .is-active-link::before {
        background-color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 20px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/Runtime/" target="_blank">
                                <span class="chip bg-color">Runtime</span>
                            </a>
                        
                            <a href="/tags/底层/" target="_blank">
                                <span class="chip bg-color">底层</span>
                            </a>
                        
                            <a href="/tags/源码/" target="_blank">
                                <span class="chip bg-color">源码</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fa fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/Runtime源码解读/" class="post-category" target="_blank">
                                Runtime源码解读
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                <div class="post-date info-break-policy">
                    <i class="fa fa-calendar-minus-o fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2019-04-23
                </div>

                
				
				
                    <div id="busuanzi_container_page_pv" class="info-break-policy">
                        <i class="fa fa-eye fa-fw"></i>阅读次数:&nbsp;&nbsp;
                        <span id="busuanzi_value_page_pv"></span>
                    </div>
				
            </div>
        </div>
        <hr class="clearfix">
        <div class="card-content article-card-content">
            <div id="articleContent">
                <p><strong>群组</strong><br><strong>欢迎加入群组,闲聊工作&amp;技术&amp;问题等</strong></p>
<p><img src="https://github.com/waitwalker/Resources/blob/master/Flutter/group/flutter_development_0923.JPG?raw=true" width="350" height="480" align="center"></p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Autorelease翻译过来就是自动释放,什么是自动释放,怎么自动释放,什么时候自动释放.这些是本文的研究重点.自动释放首先要从autoreleasepool说起.</p>
<h3 id="autoreleasepool是什么"><a href="#autoreleasepool是什么" class="headerlink" title="autoreleasepool是什么?"></a>autoreleasepool是什么?</h3><p>通过clang编译器重写以下我们的Objective-C代码:</p>
<pre><code>// autoreleasepool
    @autoreleasepool {

    }
</code></pre><p>这里我们定义了一个autoreleasepool对象,查看一下clang编译器重写后的源码:</p>
<pre><code>/* @autoreleasepool */ { __AtAutoreleasePool __autoreleasepool;

    }

// __AtAutoreleasePool声明结构
struct __AtAutoreleasePool {
  __AtAutoreleasePool() {atautoreleasepoolobj = objc_autoreleasePoolPush();}
  ~__AtAutoreleasePool() {objc_autoreleasePoolPop(atautoreleasepoolobj);}
  void * atautoreleasepoolobj;
};
</code></pre><p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;可以看到通过<strong>AtAutoreleasePool结构构造了一个 </strong>autoreleasepool实例,<strong>AtAutoreleasePool()方法被调用即执行atautoreleasepoolobj = objc_autoreleasePoolPush()方法;析构时,即超出</strong>AtAutoreleasePool的作用域,调用~__AtAutoreleasePool()方法,即即执行的是objc_autoreleasePoolPop(atautoreleasepoolobj)方法.其过程可以细分为以下过程(以objc-loadmethod.mm中调用load方法为例):</p>
<pre><code>void call_load_methods(void)
{
    static bool loading = NO;
    bool more_categories;

    loadMethodLock.assertLocked();

    // Re-entrant calls do nothing; the outermost call will finish the job.
    if (loading) return;
    loading = YES;

    // push
    void *pool = objc_autoreleasePoolPush();

    do {
        // 1. Repeatedly call class +loads until there aren&#39;t any more
        while (loadable_classes_used &gt; 0) {
            call_class_loads();
        }

        // 2. Call category +loads ONCE
        more_categories = call_category_loads();

        // 3. Run more +loads if there are classes OR more untried categories
    } while (loadable_classes_used &gt; 0  ||  more_categories);

    // pop
    objc_autoreleasePoolPop(pool);

    loading = NO;
}
</code></pre><p>因此我们可以初步总结autoreleasepool的执行过程主要有:<br>1)objc_autoreleasePoolPush()构造;<br>2)autorelease操作;<br>3)objc_autoreleasePoolPop(void <em>ctxt)析构<br>而objc_autoreleasePoolPush()和objc_autoreleasePoolPop(void </em>ctxt)内部分别调用的是:</p>
<pre><code>void *
objc_autoreleasePoolPush(void)
{
    return AutoreleasePoolPage::push();
}

void
objc_autoreleasePoolPop(void *ctxt)
{
    AutoreleasePoolPage::pop(ctxt);
}
</code></pre><p>可以看到分别调用的是AutoreleasePoolPage中的成员方法;AutoreleasePoolPage,在NSObject.mm文件中:</p>
<pre><code>// MARK: - AutoReleasepool class
class AutoreleasePoolPage
{
    // EMPTY_POOL_PLACEHOLDER is stored in TLS when exactly one pool is
    // pushed and it has never contained any objects. This saves memory
    // when the top level (i.e. libdispatch) pushes and pops pools but
    // never uses them.
#   define EMPTY_POOL_PLACEHOLDER ((id*)1)

#   define POOL_BOUNDARY nil
    static pthread_key_t const key = AUTORELEASE_POOL_KEY;
    static uint8_t const SCRIBBLE = 0xA3;  // 0xA3A3A3A3 after releasing
    static size_t const SIZE =
#if PROTECT_AUTORELEASEPOOL
        PAGE_MAX_SIZE;  // must be multiple of vm page size
#else
        PAGE_MAX_SIZE;  // size and alignment, power of 2
#endif
    static size_t const COUNT = SIZE / sizeof(id);

   // 校验完整性
    magic_t const magic;

    // next指针指向最新添加的autoreleased对象的下一个位置,初始化时指向begin()
    id *next;

    // 指向当前线程
    pthread_t const thread;

    // 父节点
    AutoreleasePoolPage * const parent;

    // 子节点
    AutoreleasePoolPage *child;

    // 节点深度
    uint32_t const depth;
    uint32_t hiwat;
}
</code></pre><p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;查看autoreleasepool的源码可以看出,autoreleasepool没有单独的内存结构,它是以 AutoreleasePoolPage为单个节点组成的双向链表来实现的.autoreleasePoolPage中一些成员变量:</p>
<pre><code>magic:校验autoreleasepoolpage结构完整性;
next:指向最新添加的autoreleased对象的下一个位置;
thread:指向当前线程;
parent:指向父节点,第一个节点parent为nil(相当于表头);
child:指向子节点,最后一个节点child为nil(相当于表尾);
</code></pre><h3 id="push-方法"><a href="#push-方法" class="headerlink" title="push()方法"></a>push()方法</h3><p>push()方法也就是创建一个autoreleasepoolpage实例的过程:</p>
<pre><code>// push
    static inline void *push()
    {
        id *dest;
        if (DebugPoolAllocation) {

            // 每一个autoreleasepool对象开始于一个新的autoreleasepoolpage
            // Each autorelease pool starts on a new pool page.
            dest = autoreleaseNewPage(POOL_BOUNDARY);
        } else {
            dest = autoreleaseFast(POOL_BOUNDARY);
        }
        assert(dest == EMPTY_POOL_PLACEHOLDER || *dest == POOL_BOUNDARY);
        return dest;
    }
</code></pre><p>其逻辑过程:</p>
<pre><code>// 创建一个page逻辑
    static inline id *autoreleaseFast(id obj)
    {
        AutoreleasePoolPage *page = hotPage();
        if (page &amp;&amp; !page-&gt;full()) {
            return page-&gt;add(obj);
        } else if (page) {
            return autoreleaseFullPage(obj, page);
        } else {
            return autoreleaseNoPage(obj);
        }
    }
</code></pre><p>其中每个page最多存储有4096个bytes:</p>
<pre><code>#define I386_PGBYTES        4096        /* bytes per 80386 page */
#define I386_PGSHIFT        12        /* bitshift for pages */

#define    PAGE_SIZE        I386_PGBYTES
</code></pre><p>当第一次创建的时候传入的是nil,所以调用autoreleaseNoPage()函数,创建一个新的page:</p>
<pre><code>static __attribute__((noinline))
    id *autoreleaseNoPage(id obj)
    {
        // &quot;No page&quot; could mean no pool has been pushed
        // or an empty placeholder pool has been pushed and has no contents yet
        assert(!hotPage());

        bool pushExtraBoundary = false;
        if (haveEmptyPoolPlaceholder()) {
            // We are pushing a second pool over the empty placeholder pool
            // or pushing the first object into the empty placeholder pool.
            // Before doing that, push a pool boundary on behalf of the pool
            // that is currently represented by the empty placeholder.
            pushExtraBoundary = true;
        }
        else if (obj != POOL_BOUNDARY  &amp;&amp;  DebugMissingPools) {
            // We are pushing an object with no pool in place,
            // and no-pool debugging was requested by environment.
            _objc_inform(&quot;MISSING POOLS: (%p) Object %p of class %s &quot;
                         &quot;autoreleased with no pool in place - &quot;
                         &quot;just leaking - break on &quot;
                         &quot;objc_autoreleaseNoPool() to debug&quot;,
                         pthread_self(), (void*)obj, object_getClassName(obj));
            objc_autoreleaseNoPool(obj);
            return nil;
        }
        else if (obj == POOL_BOUNDARY  &amp;&amp;  !DebugPoolAllocation) {
            // We are pushing a pool with no pool in place,
            // and alloc-per-pool debugging was not requested.
            // Install and return the empty pool placeholder.
            return setEmptyPoolPlaceholder();
        }

        // We are pushing an object or a non-placeholder&#39;d pool.

        // Install the first page.
        AutoreleasePoolPage *page = new AutoreleasePoolPage(nil);
        setHotPage(page);

        // Push a boundary on behalf of the previously-placeholder&#39;d pool.
        if (pushExtraBoundary) {
            page-&gt;add(POOL_BOUNDARY);
        }

        // Push the requested object or pool.
        return page-&gt;add(obj);
    }
</code></pre><p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;push()方法类似于autoreleasepool的初始化方法,先创建一个autoreleasepoolpage节点,然后想page中添加一个nil对象占位.</p>
<pre><code>dest = autoreleaseFast(POOL_BOUNDARY);
define POOL_BOUNDARY nil
</code></pre><h3 id="autorelease-方法"><a href="#autorelease-方法" class="headerlink" title="autorelease()方法"></a>autorelease()方法</h3><p>查看一下NSObject.h提供的autorelease方法接口,其调用栈:</p>
<pre><code>- (instancetype)autorelease OBJC_ARC_UNAVAILABLE;

// Replaced by ObjectAlloc
- (id)autorelease {
    return ((id)self)-&gt;rootAutorelease();
}

// MARK: - autorelease 实现
// Base autorelease implementation, ignoring overrides.
inline id
objc_object::rootAutorelease()
{
    if (isTaggedPointer()) return (id)this;
    if (prepareOptimizedReturn(ReturnAtPlus1)) return (id)this;

    return rootAutorelease2();
}

__attribute__((noinline,used))
id
objc_object::rootAutorelease2()
{
    assert(!isTaggedPointer());
    return AutoreleasePoolPage::autorelease((id)this);
}

</code></pre><p>可以看到autorelease最终调用的是AutoreleasePoolPage中的成员方法autorelease();</p>
<pre><code>// autorelease
    static inline id autorelease(id obj)
    {
        assert(obj);
        assert(!obj-&gt;isTaggedPointer());
        id *dest __unused = autoreleaseFast(obj);
        assert(!dest  ||  dest == EMPTY_POOL_PLACEHOLDER  ||  *dest == obj);
        return obj;
    }
</code></pre><p>AutoreleasePoolPage中的成员方法autorelease()内部调用的是:</p>
<pre><code>static inline id *autoreleaseFast(id obj)
    {
        AutoreleasePoolPage *page = hotPage();
        if (page &amp;&amp; !page-&gt;full()) {
            return page-&gt;add(obj);
        } else if (page) {
            return autoreleaseFullPage(obj, page);
        } else {
            return autoreleaseNoPage(obj);
        }
    }
</code></pre><p>其逻辑是:<br>1)先判断当前page存在并且没满,则将released obj 添加到当前page;<br>2)如果当前page已满,则创建一个新的page,并将当前page的child指针指向new page;把released obj 添加到new page中;</p>
<pre><code>// MARK: - 创建一个new page
    static __attribute__((noinline))
    id *autoreleaseFullPage(id obj, AutoreleasePoolPage *page)
    {
        // The hot page is full.
        // Step to the next non-full page, adding a new page if necessary.
        // Then add the object to that page.
        assert(page == hotPage());
        assert(page-&gt;full()  ||  DebugPoolAllocation);

        do {
            if (page-&gt;child) page = page-&gt;child;
            else page = new AutoreleasePoolPage(page);
        } while (page-&gt;full());

        setHotPage(page);
        return page-&gt;add(obj);
    }
</code></pre><p>3)如果当前page不存在,则直接创建一个new page,并把released obj添加到new page中;没有page意味着autoreleasepool没有进行push操作或者autoreleasepool已经push操作了,但是没有添加任何released的obj或者添加的是nil对象,则创建一个空的autoreleasepool进行占位;</p>
<pre><code>// autoreleasepool中没有page
    static __attribute__((noinline))
    id *autoreleaseNoPage(id obj)
    {
        // &quot;No page&quot; could mean no pool has been pushed
        // or an empty placeholder pool has been pushed and has no contents yet
        assert(!hotPage());

        bool pushExtraBoundary = false;
        if (haveEmptyPoolPlaceholder()) {
            // We are pushing a second pool over the empty placeholder pool
            // or pushing the first object into the empty placeholder pool.
            // Before doing that, push a pool boundary on behalf of the pool
            // that is currently represented by the empty placeholder.
            pushExtraBoundary = true;
        }
        else if (obj != POOL_BOUNDARY  &amp;&amp;  DebugMissingPools) {//如果没有创建一个autoreleasepool,则直接抛异常
            // We are pushing an object with no pool in place,
            // and no-pool debugging was requested by environment.
            _objc_inform(&quot;MISSING POOLS: (%p) Object %p of class %s &quot;
                         &quot;autoreleased with no pool in place - &quot;
                         &quot;just leaking - break on &quot;
                         &quot;objc_autoreleaseNoPool() to debug&quot;,
                         pthread_self(), (void*)obj, object_getClassName(obj));
            objc_autoreleaseNoPool(obj);
            return nil;
        }
        else if (obj == POOL_BOUNDARY  &amp;&amp;  !DebugPoolAllocation) {//如果对象为空,并非debug环境,创建一个空的autore占位
            // We are pushing a pool with no pool in place,
            // and alloc-per-pool debugging was not requested.
            // Install and return the empty pool placeholder.
            return setEmptyPoolPlaceholder();
        }

        // We are pushing an object or a non-placeholder&#39;d pool.

        // Install the first page.
        AutoreleasePoolPage *page = new AutoreleasePoolPage(nil);
        setHotPage(page);

        // Push a boundary on behalf of the previously-placeholder&#39;d pool.
        if (pushExtraBoundary) {
            page-&gt;add(POOL_BOUNDARY);
        }

        // 将released obj添加到page中
        // Push the requested object or pool.
        return page-&gt;add(obj);
    }
</code></pre><p>以上三个过程都有执行add()操作,具体看一下add():</p>
<pre><code>// 向page中添加released操作
    id *add(id obj)
    {
        assert(!full());
        unprotect();

        // 将next节点赋值给ret
        id *ret = next;  // faster than `return next-1` because of aliasing

        // next指针增大一个位置
        *next++ = obj;
        protect();
        return ret;
    }
</code></pre><p>向一个对象发送一条 -autorelease消息,其实就是将这个对象加入到AutoreleasePoolPage中next指针指向的位置,然后next增大一个位置.</p>
<h3 id="pop-方法"><a href="#pop-方法" class="headerlink" title="pop()方法"></a>pop()方法</h3><p>pop操作上面已经提到了是autoreleasepool的析构函数也就是page的销毁函数.</p>
<pre><code>// pop
    static inline void pop(void *token)
    {
        AutoreleasePoolPage *page;
        id *stop;

        // 如果当前obj是nil
        if (token == (void*)EMPTY_POOL_PLACEHOLDER) {
            // Popping the top-level placeholder pool.
            if (hotPage()) {
                // Pool was used. Pop its contents normally.
                // Pool pages remain allocated for re-use as usual.
                pop(coldPage()-&gt;begin());
            } else {
                // Pool was never used. Clear the placeholder.
                setHotPage(nil);
            }
            return;
        }

        // 根据token获取page
        page = pageForPointer(token);
        stop = (id *)token;
        if (*stop != POOL_BOUNDARY) {
            if (stop == page-&gt;begin()  &amp;&amp;  !page-&gt;parent) {
                // Start of coldest page may correctly not be POOL_BOUNDARY:
                // 1. top-level pool is popped, leaving the cold page in place
                // 2. an object is autoreleased with no pool
            } else {
                // Error. For bincompat purposes this is not
                // fatal in executables built with old SDKs.
                return badPop(token);
            }
        }

        if (PrintPoolHiwat) printHiwat();

        // 释放对象 沿着链表向上查找
        page-&gt;releaseUntil(stop);

        // memory: delete empty children
        if (DebugPoolAllocation  &amp;&amp;  page-&gt;empty()) {
            // special case: delete everything during page-per-pool debugging
            AutoreleasePoolPage *parent = page-&gt;parent;
            page-&gt;kill();
            setHotPage(parent);
        } else if (DebugMissingPools  &amp;&amp;  page-&gt;empty()  &amp;&amp;  !page-&gt;parent) {
            // special case: delete everything for pop(top)
            // when debugging missing autorelease pools
            page-&gt;kill();
            setHotPage(nil);
        }
        else if (page-&gt;child) {
            // hysteresis: keep one empty child if page is more than half full
            if (page-&gt;lessThanHalfFull()) {
                page-&gt;child-&gt;kill();
            }
            else if (page-&gt;child-&gt;child) {
                page-&gt;child-&gt;child-&gt;kill();
            }
        }
    }
</code></pre><p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;pop()函数有个参数是push()操作的返回值即next指针指向内存地址.然后拿到这个地址遍历链表遍历当前page,然后向page中的obj发送release消息,直到next指向nil:</p>
<pre><code>// MARK: - 释放obj
    void releaseUntil(id *stop)
    {
        // Not recursive: we don&#39;t want to blow out the stack
        // if a thread accumulates a stupendous amount of garbage

        // 遍历链表
        while (this-&gt;next != stop) {
            // Restart from hotPage() every time, in case -release
            // autoreleased more objects
            AutoreleasePoolPage *page = hotPage();

            // fixme I think this `while` can be `if`, but I can&#39;t prove it

            // 获取page的父指针
            while (page-&gt;empty()) {
                page = page-&gt;parent;
                setHotPage(page);
            }

            page-&gt;unprotect();

            // 根据next指针缩小一个位置获取obj
            id obj = *--page-&gt;next;
            memset((void*)page-&gt;next, SCRIBBLE, sizeof(*page-&gt;next));
            page-&gt;protect();

            if (obj != POOL_BOUNDARY) {

                // 发送release 消息
                objc_release(obj);
            }
        }

        setHotPage(this);

#if DEBUG
        // we expect any children to be completely empty
        for (AutoreleasePoolPage *page = child; page; page = page-&gt;child) {
            assert(page-&gt;empty());
        }
#endif
    }
</code></pre><h3 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h3><p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;AutoreleasePoolPage是双链表的一个节点,其内部有可以理解为一个存储released obj地址的堆栈容器,每一个新加入的released obj被添加到这个容器里面,然后有一个next指针指向最后被加入的obj地址的下一个位置.如果当前page SIZE 满了,创建一个新的page. pop()操作就是获取到page中的每一个obj,给他们发送release()消息.</p>
<h3 id="编译后源码库"><a href="#编译后源码库" class="headerlink" title="编译后源码库"></a>编译后源码库</h3><p><strong>编译后的源码放在<a href="https://github.com/waitwalker/Runtime" target="_blank" rel="noopener">Github</a>, 如果对你有帮助,请给一个star吧!</strong></p>
<h3 id="博客地址-amp-相关文章"><a href="#博客地址-amp-相关文章" class="headerlink" title="博客地址&amp;相关文章"></a>博客地址&amp;相关文章</h3><p><strong>博客地址:</strong> <a href="https://waitwalker.cn/" target="_blank" rel="noopener">https://waitwalker.cn/</a></p>
<p>系列文章:</p>
<p><a href="https://waitwalker.github.io/2019/04/08/Runtime%E6%BA%90%E7%A0%81%E7%BC%96%E8%AF%91/">1. Runtime源码编译</a></p>
<p><a href="https://waitwalker.github.io/2019/04/10/objc-object%E8%A7%A3%E8%AF%BB/">2. objc_object解读</a></p>
<p><a href="https://waitwalker.github.io/2019/04/12/Method%E8%A7%A3%E8%AF%BB/">3. Method解读</a></p>
<p><a href="https://waitwalker.github.io/2019/04/15/Class%E8%A7%A3%E8%AF%BB/">4. Class解读</a></p>
<p><a href="https://waitwalker.github.io/2019/04/15/Ivar-objc-property-t-Protocol%E8%A7%A3%E8%AF%BB/">5. Ivar objc_property_t Protocol解读</a></p>
<p><a href="https://waitwalker.github.io/2019/04/18/Block解读/">6. Block解读</a></p>
<p><a href="http://waitwalker.cn/2019/04/22/Retain-Release解读/" target="_blank" rel="noopener">7. Retain&amp;Release解读</a></p>
<p><a href="http://waitwalker.cn/2019/04/23/Autorelease解读/" target="_blank" rel="noopener">8. Autorelease解读</a></p>
<p><a href="http://waitwalker.cn/2019/04/24/Weak解读/" target="_blank" rel="noopener">9. Weak解读</a></p>
<p><a href="http://waitwalker.cn/2019/04/25/msgSend-解读/" target="_blank" rel="noopener">10. msgSend()解读</a></p>
<h3 id="参考文献"><a href="#参考文献" class="headerlink" title="参考文献"></a>参考文献</h3><p>《Objective-C高级编程：iOS与OS X多线程和内存管理》(Pro multithreading and memory management for iOS and OS X)–译者: 黎 华</p>

            </div>
            <hr>

            
            <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.88rem;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-large waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fa fa-close"></i></a>
            <h4 class="reward-title">你的赏识是我前进的动力</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="/medias/reward/alipay.jpg" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="/medias/reward/wechat.png" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>
            

            <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">

<div id="article-share">
    
    <div class="social-share" data-disabled="qzone" data-wechat-qrcode-helper="<p>微信里点“发现”->“扫一扫”二维码便可查看分享。</p>"></div>
    
</div>

<script src="/libs/share/js/social-share.min.js"></script>

            <div class="reprint">
                <p>
                    <span class="reprint-tip">
                        <i class="fa fa-exclamation-circle"></i>&nbsp;&nbsp;转载请注明:
                    </span>
                    <a href="https://waitwalker.github.io" class="b-link-green">waitwalker</a>
                    <i class="fa fa-angle-right fa-lg fa-fw text-color"></i>
                    <a href="/2019/04/23/Autorelease解读/" class="b-link-green">Autorelease解读</a>
                </p>
            </div>
        </div>
    </div>

    

    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6 overflow-policy" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fa fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/2019/04/24/Weak解读/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/16.jpg" class="responsive-img" alt="Weak解读">
                        
                        <span class="card-title">Weak解读</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">群组欢迎加入群组,闲聊工作&amp;技术&amp;问题等

在常规开发中我们经常使用__weak修饰符来修饰一个对象,来解决比如循环引用问题.今天具体来看看weak底层实现原理.
首先创建一个weak修饰的对象,并查看其调用栈:

int </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="fa fa-clock-o fa-fw icon-date"></i>2019-04-24
                        </span>
                        <span class="publish-author">
                            
                            <i class="fa fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/Runtime源码解读/" class="post-category" target="_blank">
                                    Runtime源码解读
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/Runtime/" target="_blank">
                        <span class="chip bg-color">Runtime</span>
                    </a>
                    
                    <a href="/tags/iOS/" target="_blank">
                        <span class="chip bg-color">iOS</span>
                    </a>
                    
                    <a href="/tags/source-code/" target="_blank">
                        <span class="chip bg-color">source code</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6 overflow-policy" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fa fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/2019/04/22/Retain-Release解读/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/6.jpg" class="responsive-img" alt="Retain&Release解读">
                        
                        <span class="card-title">Retain&Release解读</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">群组欢迎加入群组,闲聊工作&amp;技术&amp;问题等

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;iOS通过引用计数(Reference Counting)机制来管理内存,当一个对象</div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="fa fa-clock-o fa-fw icon-date"></i>2019-04-22
                            </span>
                        <span class="publish-author">
                            
                            <i class="fa fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/Runtime源码解读/" class="post-category" target="_blank">
                                    Runtime源码解读
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/Runtime/" target="_blank">
                        <span class="chip bg-color">Runtime</span>
                    </a>
                    
                    <a href="/tags/底层/" target="_blank">
                        <span class="chip bg-color">底层</span>
                    </a>
                    
                    <a href="/tags/源码/" target="_blank">
                        <span class="chip bg-color">源码</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>
</div>


<script>
    $('#articleContent').on('copy', function (e) {
        // IE8 or earlier browser is 'undefined'
        if (typeof window.getSelection === 'undefined') return;

        var selection = window.getSelection();
        // if the selection is short let's not annoy our users.
        if (('' + selection).length < Number.parseInt('120')) {
            return;
        }

        // create a div outside of the visible area and fill it with the selected text.
        var bodyElement = document.getElementsByTagName('body')[0];
        var newdiv = document.createElement('div');
        newdiv.style.position = 'absolute';
        newdiv.style.left = '-99999px';
        bodyElement.appendChild(newdiv);
        newdiv.appendChild(selection.getRangeAt(0).cloneContents());

        // we need a <pre> tag workaround.
        // otherwise the text inside "pre" loses all the line breaks!
        if (selection.getRangeAt(0).commonAncestorContainer.nodeName === 'PRE') {
            newdiv.innerHTML = "<pre>" + newdiv.innerHTML + "</pre>";
        }

        var url = document.location.href;
        newdiv.innerHTML += '<br />'
            + '来源: waitwalker<br />'
            + '作者: waitwalker<br />'
            + '链接: <a href="' + url + '">' + url + '</a><br />'
            + '本文章著作权归作者所有，任何形式的转载都请注明出处。';

        selection.selectAllChildren(newdiv);
        window.setTimeout(function () {bodyElement.removeChild(newdiv);}, 200);
    });
</script>

    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget">
            <div class="toc-title"><i class="fa fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fa fa-list"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            // headingsOffset: -205,
            headingSelector: 'h2, h3, h4'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h2, h3, h4').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).slideUp(500);
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).slideDown(500);
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>
    

</main>


<footer class="page-footer bg-color">
    <div class="container row center-align">
        <div class="col s12 m8 l8 copy-right">
            本站在原作者&copy;<a href="https://blinkfox.github.io/" target="_blank">Blinkfox</a>基于
            <a href="https://hexo.io/" target="_blank">Hexo</a> 的
            <a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">hexo-theme-matery</a>主题基础上搭建.

            

            
			
                <br>
                
                <span id="busuanzi_container_site_pv">
                    <i class="fa fa-heart-o"></i>
                    本站总访问量 <span id="busuanzi_value_site_pv" class="white-color"></span>
                </span>
                
                
                <span id="busuanzi_container_site_uv">
                    <i class="fa fa-users"></i>
                    次,&nbsp;访客数 <span id="busuanzi_value_site_uv" class="white-color"></span> 人.
                </span>
                
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis"><!---->
<a href="https://github.com/waitwalker" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
    <i class="fa fa-github"></i>
</a>

<a href="https://twitter.com/284485487" class="tooltipped" target="_blank" data-tooltip="Twitter联系我" data-position="top" data-delay="50">
    <i class="fa fa-twitter"></i>
</a>

<a href="https://www.facebook.com/profile.php?id=100003684945279" class="tooltipped" target="_blank" data-tooltip="Twitter联系我" data-position="top" data-delay="50">
    <i class="fa fa-facebook"></i>
</a>

<a href="https://t.me/joinchat/Ej0o0A1ntlq5ZFIMzzO5Pw" class="tooltipped" target="_blank" data-tooltip="Twitter联系我" data-position="top" data-delay="50">
    <i class="fa fa-telegram"></i>
</a>

<a href="https://www.weibo.com/1789419613/profile?topnav=1&wvr=6&is_all=1" class="tooltipped" target="_blank" data-tooltip="Twitter联系我" data-position="top" data-delay="50">
    <i class="fa fa-weibo"></i>
</a>


<!--原来-->
<!---->
    <!--<a href="mailto:waitwalker@163.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">-->
        <!--<i class="fa fa-envelope-open"></i>-->
    <!--</a>-->
<!---->

<!---->
    <!--<a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=284485487" class="tooltipped" data-tooltip="QQ联系我: 284485487" data-position="top" data-delay="50">-->
        <!--<i class="fa fa-qq"></i>-->
    <!--</a>-->
<!---->

<!---->
    <!--<a href="/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">-->
        <!--<i class="fa fa-rss"></i>-->
    <!--</a>-->
<!----></div>
    </div>
</footer>

<div class="progress-bar"></div>


<!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fa fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字" class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script src="/js/search.js"></script>
<script type="text/javascript">
$(function () {
    searchFunc("/" + "search.xml", 'searchInput', 'searchResult');
});
</script>
<!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fa fa-angle-up"></i>
    </a>
</div>


<script src="/libs/materialize/materialize.min.js"></script>
<script src="/libs/masonry/masonry.pkgd.min.js"></script>
<script src="/libs/aos/aos.js"></script>
<script src="/libs/scrollprogress/scrollProgress.min.js"></script>
<script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
<script src="/js/matery.js"></script>

<!-- Global site tag (gtag.js) - Google Analytics -->




    <script async src="/libs/others/busuanzi.pure.mini.js"></script>


</body>
</html>